<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract AJAX常用功能封装
 * @author zxj
 * @description
 */
class Com_ajax extends CI_Controller
{
    public $users = '';

    function __construct()
    {
        parent::__construct();
        $this->load->helper('curl');
        $this->users = $this->session->userdata('users');
    }

    /**
     * 更新自定义手工费价格
     */
    function setLaborPrice()
    {
        $datas = gp();
        if(!$datas['id'])exit('0');
        $this->common_model->update('mt_customer_price', array('price' => $datas['newPrice']), array('id' => $datas['id']));
        exit('1');
    }


    /*** 更新运费
     */
    function setShippingFee()
    {
        $datas = gp();
        if ($datas['shippingFeeText'] === '') {
            exit('error,运费不能为空');
        } elseif (!$datas['oid']) {
            exit('error,维修单不能为空');
        }
        $this->common_model->update('mt_order', array('shippingFeeText' => $datas['shippingFeeText']), array('id' => $datas['oid']));
        exit('succeed,添加运费成功,可以质检');
    }


    /**
     * 更新追踪号
     */
    function setShipoutTrack()
    {
        $datas = gp();
        if ($datas['shipoutTrack'] === '') {
            exit('error,追踪号不能为空');
        } elseif (!$datas['oid2']) {
            exit('error,维修单不能为空');
        }
        $this->common_model->update('mt_order', array('shipoutTrack' => $datas['shipoutTrack']), array('id' => $datas['oid2']));
        exit('succeed,添加追踪号成功,可以发货');
    }


    /**
     * 货币汇率换算
     */
    function currency_service()
    {
        $gpData = gp();
        $result = currency_service($gpData['formCur'], $gpData['toCur'], $gpData['amount'], $gpData['is_ary']);
        echo json_encode($result), exit;
    }


    /**
     * 获取配件列表
     */
    function getPartsList()
    {
        //#接受数据
        $gpData = gp();
        $lang = $this->uri->segment(1);
        $point = $gpData['point'];
        $orderFirst = $this->common_model->selectFirst('mt_order', array('id' => $gpData['oid']));
        if ($gpData['pid']) {
            $productFirst = $this->common_model->selectFirst('mt_product', array('id' => $gpData['pid']));
            $brandCustomerNum = $productFirst['brandCustomerNum'];
            $inWarranty=$productFirst['inWarranty'];
        }
        if (!$point) {
            $SCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $orderFirst['service_center']));
            $point = $SCenter['point'];
        }
        //所需数量，目前默认是1
        $quantity=1;
        //搜索关键字
        $keyword=$gpData['keyword'];
        //维修点所属商家
        $merchant_num=$brandCustomerNum;
        //position
        $parts_id=$gpData['position'];
        //物料号
        $sku=$gpData['sku'];
        //
        
        //加载获取配件列表service
        $this->load->service('wms/api_service');
        //全局
        if($gpData['scope']==1) {
            /**
             * WMS代替获取列表
             * 
            $url = 'http://stock.dhhtgroup.com/webService/GetComponentsByPar.php';
            $postData = array(
                'account' => 'Tomrepair666', 'token' => 'TomrepairAccessory', 'data' => $gpData['keyword'],
            );
            $result = vpost($url, $postData);
            $result = json_decode($result, true);
             * 
             */
               $result=$this->api_service->get_all_parts($point, $orderFirst['merchant_num'], $inWarranty, $quantity, $keyword,$productFirst['brandCustomerNum']);

            if (!$result['success']) exit('');
            $partsList = $result['message'];
        }else{//局部
            
           /**
            if(ENVIRONMENT == 'development') {
                $url = 'http://test.dhhtgroup.com:8889/webService/GetAccessoryDateByAppModel.php';
            }else {
                $url = 'http://stock.dhhtgroup.com/webService/GetAccessoryDateByAppModel.php';
            }
            $data = array(
                'account'=>'oms',
                'token'=>'oms123!@#',
                'data'=>json_encode(array(
                    'sku'=>$gpData['sku'],
                    'typeId'=>'',
                    'brandId'=>'',
                    'modelId'=>'',
                    'keyword'=>$gpData['keyword'],
                    'partsId'=>$gpData['position'])
                )
            );
            $result=CurlPost($url,$data);
            * 
            */
            
            $result=$this->api_service->get_parts($point,$orderFirst['merchant_num'], $inWarranty, $quantity, $parts_id, $keyword, $sku, $type_id='', $brand_id='', $model_id='',$productFirst['brandCustomerNum']);
            if (!$result['success']) {
                $partsList=array();
                echo 'nothing';
                exit;
            }else {
                $partsList = $result['data'];
            }
        }
        foreach ($partsList as &$rs) {
            if ($lang == 'sc' && $rs['products_name_cn']) {
                $rs['name'] = $rs['products_name_cn'];
            } else {
                $rs['name'] = $rs['products_name'] ? $rs['products_name'] : $rs['products_name_cn'];
            }
            $rs['quantity'] = $rs['inventory'][0]['quantity'];
            $rs['price'] = $rs['products_price'];
            $rs['cost_price'] = $rs['products_cost'];
            $rs['point'] = $point;
            $rs['whs_code'] = $rs['inventory'][0]['whs_code'];
            $rs['type'] = $rs['inventory'][0]['type'];
            $rs['brandCustomerNum'] = $brandCustomerNum;
            $rs['model_id'] = $productFirst['model_id'];
            $rs['jsonData'] = urlencode(json_encode($rs));
        }
        unset($rs);
        $data['partsList'] = $partsList;
        $data['viewType'] = 'getPartsList';
        $this->load->view('defaults/ajax_parts_list', $data);
    }


    /**
     * 获取配件库存
     */
    function getPartStock()
    {
        $gpData = gp();
        $url = 'http://stock.dhhtgroup.com/webService/GetComponentsByPar.php';
        $point = $gpData['point'];
        $sap_sku = $gpData['sap_sku'];
        $brandCustomerNum = $gpData['brandCustomerNum'];
        $model_id = $gpData['model_id'];
        $this->load->library('OmsQuery');
        $omsQuery = new OmsQuery();
        $point_num = $omsQuery->GetSiteNum($point);
        //获取虚拟仓代码
        $code = $omsQuery->GetVirtualWarehouseCode($point_num, $brandCustomerNum, $model_id);
        if ($code == '') {
            $code = $omsQuery->GetMaintenanceWarehouseCode($point);
        }
        $postData = array(
            'account' => 'Tomrepair666', 'token' => 'TomrepairAccessory',
            'stockName' => $code, 'sap_sku' => $sap_sku
        );
        $result = vpost($url, $postData);
        $result = json_decode($result, true);
        echo (int)$result['message'];
        exit;
    }


    /**
     * 维修项手工费
     */
    function laborPrice()
    {
        $formData = gp();
        if(is_array($formData)&& array_sum($formData)==0)exit;
        $fieldsList = $this->db->list_fields('mt_customer_price');
        $where = array();
        foreach ($formData as $key=>$val) {
            if($val && in_array($key,$fieldsList))$where[$key]=$val;
        }
        $laborList = $this->common_model->selectCustom('mt_customer_price', $where);
        if(!$laborList){
            unset($where['customer_id']);
            unset($where['brand_id']);
            $laborList = $this->common_model->selectCustom('mt_base_price',$where);

        }
        foreach ($laborList as &$rs) {
            $repairItem = $this->common_model->selectFirst('mt_product_repair_item',array('id'=>$rs['labor_id']));
            $rs['repairItem'] = $repairItem['name_ch'];
            $siteCenter = $this->common_model->selectFirst('mt_service_center',array('id'=>$rs['site_id']));
            $rs['siteName'] = $siteCenter['name_ch'];
            $rs['currency'] = $siteCenter['currency'];
            $rs['laborPrice'] = $rs['price']?$rs['price']:$rs['merchant_price'];
        }
        unset($rs);
        $data['laborList'] = $laborList;
        $this->load->view('defaults/laborPrice_List', $data);
    }


    /**
     * 添加配件
     */
    function addParts()
    {
        //接收数据
        $formData = gp();
        if (!$formData) {
            show_error(__FILE__ . 'Did not get the data');
        }
        $orderFirst = $this->common_model->selectFirst('mt_order', array('id' => $formData['oid']));
        //#添加配件
        $fieldsList = $this->db->list_fields('mt_product_parts');
        $inData = array();
        $inData['point'] = $orderFirst['point'];
        if($formData['name_select']){
            $json=json_decode(urldecode($formData['name_select']),true);
            $formData['name']=$json['name'];
        }
        foreach ($formData as $key => $val) {
            if (!in_array($key, $fieldsList)) continue;
            $inData[$key] = trim($val);
        }
        //#价格处理
        $inData['rate_currency'] = $orderFirst['currency_code'];
        $inData['rate_price'] = $inData['price'];
        if ($inData['price'] > 0 && $inData['currency'] != $orderFirst['currency_code']) {
            $inData['rate_price'] = currency_service($inData['currency'], $inData['rate_currency'], $inData['price']);
        }
        //#补充报价
        if ($orderFirst['is_pay']) {
            $inData['isSupplement'] = 1;
        }
        //基础数据
        $inData['add_user'] = $this->users['name'];
        $inData['add_time'] = time();
        //#数量处理
        $formData['stockQuantity'] = max(intval($formData['stockQuantity']), 0);;
        $inData['quantity'] = max(intval($inData['quantity']), 1);
      if($orderFirst['napa_stores_num']){
          //加载锁定库存service
            $this->load->service('/wms/inventory_on_order_service');
            //正常配件
            $inData['status'] = 1;
            $partsId = $this->common_model->insert('mt_product_parts', $inData);
            /*if ($partsId)
            {
                //加盟商的订单锁定WMS可用库存
                $setOk = $this->inventory_on_order_service->set_onorder_product_parts($inData, $orderFirst['napa_stores_num']);
                //锁定可用库存失败删除配件
                if (true !== $setOk)
                {
                    $this->common_model->delete('mt_product_parts', array('id' => $partsId));
                    js_goto('加盟商库存不足!');
                }
            }*/
      }elseif (!$inData['sku'] || $inData['price']<=0) {
            //待处理数量
            $inData['status'] = 2;
            $partsId = $this->common_model->insert('mt_product_parts', $inData);
            //ERP生成处理需求
            $this->common_model->createPartsNeed($partsId);
        } else {
            if ($inData['quantity'] <= $formData['stockQuantity']) {
                //可用数量,应扣减库存
                $inData['status'] = 1;
                $partsId=$this->common_model->insert('mt_product_parts', $inData);
                if($orderFirst['napa_stores_num']){
                    //加载锁定库存service
                    $this->load->service('/wms/on_order_service');
                    if ($partsId)
                    {
                        //加盟商的订单锁定WMS可用库存
                        $setOk = $this->on_order_service->set_onorder_product_parts($inData, $orderFirst['napa_stores_num']);
                        //锁定可用库存失败删除配件
                        if (true !== $setOk)
                        {
                            $this->common_model->delete('mt_product_parts', array('id' => $partsId));
                        }
                    }
                }
            } elseif ($formData['stockQuantity'] > 0) {
                //待采购数量
                $inData['quantity'] = $inData['quantity'] - $formData['stockQuantity'];
                $inData['status'] = 3;
                $partsId = $this->common_model->insert('mt_product_parts', $inData);
                //可用数量,扣减库存
                $inData['quantity'] = $formData['stockQuantity'];
                $inData['status'] = 1;
                $this->common_model->insert('mt_product_parts', $inData);
            } else {
                //待采购数量
                $inData['status'] = 3;
                $partsId = $this->common_model->insert('mt_product_parts', $inData);
            }
        }
        //#更新价格
        //$this->common_model->setProductPrice($formData['pid']);
        $this->partsList($formData['pid']);

    }


    /**
     * 配件列表
     * @param string $id
     */
    function partsList($id = '')
    {
        $id = $id ? intval($id) : gp('id');
        //配件列表
        $partsList = $this->common_model->selectCustom('mt_product_parts', array('pid' => $id));
        foreach ($partsList as &$rs) {
            $rs['nameSub'] = mb_substr($rs['name'], 0, 20) . '...';
            if ($rs['status'] == 2) {
                $rs['statusName'] = 'pending';
            } elseif ($rs['status'] == 3) {
                $rs['statusName'] = 'wait purchase';
            } else {
                $rs['statusName'] = 'Normal';
            }
            $rs['price'] = $rs['price'] . ' ' . $rs['currency'];
            $rs['rate_price'] = $rs['rate_price'] . ' ' . $rs['rate_currency'];
            $rs['isSupplementName'] = $rs['isSupplement'] ? "Y" : 'N';
        }
        unset($rs);
        $data['partsList'] = $partsList;
        $data['viewType'] = 'partsList';
        $this->load->view('defaults/ajax_parts_list', $data);
    }


    /**
     * 删除配件
     */
    function delParts()
    {
        $id = intval(gp('id'));
        //配件信息
        $partsOne = $this->common_model->selectFirst('mt_product_parts', array('id' => $id));
        if (!$partsOne) {
            json_output($partsOne, '非法操作,配件不存在', false);
        }
        //订单信息
        $orderFirst = $this->common_model->selectFirst('mt_order', array('id' => $partsOne['oid']));
        $products = $this->common_model->selectFirst('mt_product', array('id' => $partsOne['pid']));
        if (!$partsOne['isSupplement'] && $products['acceptQuotation']) {
            json_output($products, '已同意报价,删除失败', false);
        } elseif ($partsOne['isSupplement'] && $products['supplementAcceptQuotation']) {
            json_output($products, '已同意补充报价,删除失败', false);
        }
        //#减库存
        $isde=$this->common_model->delete('mt_product_parts', array('id' => $id));
        //这里暂时先用1=2跳过判断，以后wms上线之后再行启用 sqingwen 20170320 1540
        if(1==2&&$isde&&''!=$orderFirst['napa_stores_num']){
          //加载锁定库存service
            $this->load->service('/wms/on_order_service');
            //减少可用库存
              $partsInfo=$partsOne;
              $partsInfo['quantity']=0-$partsInfo['quantity'];
              $this->inventory_on_order_service->set_onorder_product_parts($partsInfo, $orderFirst['napa_stores_num']);
        }
        //更新状态
        if ($products['status_id'] == 4) {
            $this->common_model->resetStatus($products['id']);
        }
        //取消采购
        $this->cancelPurchase($id);
        $this->partsList($partsOne['pid']);
    }


    /**
     * 占用配件库存
     * @param string $id
     * @return bool
     */
    function occupyStockParts($id = '')
    {
        $id = intval($id);
        $partsOne = $this->common_model->selectFirst('mt_product_parts', array('id' => $id));
        if (!$partsOne) return false;
        //$url = 'http://stock.dhhtgroup.com/webService/AccessoryInventoryLock.php';
        $url = 'http://sun.erp.com:8889/webService/AccessoryInventoryLock.php';
        $dataArr = array(
            'orderId' => $partsOne['oid'], 'sku' => $partsOne['sku'], 'quantity' => $partsOne['quantity']
        );
        $data = array(
            'account' => 'Tomrepair666', 'token' => 'TomrepairAccessoryInventoryLockToken',
            'data' => json_encode($dataArr)
        );
        $result = vpost($url, $data);
        echo $result;
        return true;
    }


    /**
     * 释放配件库存
     * @param string $id
     * @return bool
     */
    function freeStockParts($id = '')
    {
        $id = intval($id);
        $partsOne = $this->common_model->selectFirst('mt_product_parts', array('id' => $id));
        //$url = 'http://stock.dhhtgroup.com/webService/AccessoryInventoryUnlock.php';
        $url = 'http://sun.erp.com:8889/webService/AccessoryInventoryUnlock.php';
        $dataArr = array('orderId' => 'test', 'sku' => 'pru46744_lcd', 'quantity' => '1');
        $data = array(
            'account' => 'Tomrepair666',
            'token' => 'TomrepairAccessoryInventoryUnlockToken',
            'data' => json_encode($dataArr));
        return true;
    }


    /**
     * 验证是否有添加配件
     */
    function verifyIsPart()
    {
        $gp = gp();
        $id = $gp['id'];
        $partsList = $this->common_model->selectCustom('mt_product_parts', array('pid' => $id));
        //维修项验证
        $itemArr = $gp['itemArr'];
        $isReplaceParts = $this->common_model->selectCustom('mt_product_repair_item', array('category' => 1, 'isReplaceParts' => 1), 'id desc', array('id' => $itemArr));
        if($isReplaceParts && !$partsList){
            json_output('-1',lang('order_qxtjpj'),false);
        }elseif (!$partsList) {
            json_output('-2', lang('order_mypjsfjx'), false);
        }
        json_output('1', 'already existing', true);
    }

    /**
     * 取消采购
     * @param $id
     */
    function cancelPurchase($id){
        if(ENVIRONMENT == 'development'){
            $url = 'http://47.90.55.9:8889/webService/cancelAccessoryPurchaseNewOrder.php';
        }else{
            $url = 'http://stock.dhhtgroup.com/webService/cancelAccessoryPurchaseNewOrder.php';
        }
        $data = array(
            'account'=>'tomrepair',
            'token'=>'tomrepairAccessoryPurshase',
            'data'=>json_encode(array($id))
        );
        $result=CurlPost($url,$data);
        if($result['success']){
            $this->common_model->update('mt_product_parts',array('sap_status'=>4),array('id'=>$id));
        }
    }

    /**
     * 获取部分配件
     */
    public function getPortionPart(){
        $gp=gp();
        $lang = $this->uri->segment(1);
        $this->load->service('wms/api_service');
        $result=$this->api_service->get_parts($gp['point'], $gp['merchant_num'], $gp['inWarranty'], 1, $gp['position'], '', $gp['sku'],'','','',$gp['brandCustomerNum']);
        if($result['data']) {
            $partsList=$result['data'];
            foreach ($partsList as &$rs) {
                if ($lang == 'sc' && $rs['products_name_cn']) {
                    $rs['name'] = $rs['products_name_cn'];
                } else {
                    $rs['name'] = $rs['products_name'] ? $rs['products_name'] : $rs['products_name_cn'];
                }
                $rs['quantity'] = $rs['inventory'][0]['quantity'];
                $rs['price'] = $rs['products_price'];
                $rs['cost_price'] = $rs['products_cost'];
                $rs['point'] = $gp['point'];
                $rs['whs_code'] = $rs['inventory'][0]['whs_code'];
                $rs['type'] = $rs['inventory'][0]['type'];
                $rs['brandCustomerNum'] = $gp['brandCustomerNum'];
                $rs['model_id'] = $gp['model_id'];
                $rs['jsonData'] = urlencode(json_encode($rs));
            }
            unset($rs);
            echo json_encode($partsList);
        }else{
            echo '';
        }
    }

}
